import { createRouter, createWebHashHistory } from 'vue-router'
import type { RouteRecordMultipleViews, RouteRecordMultipleViewsWithChildren, RouteRecordRedirect, RouteRecordSingleView, RouteRecordSingleViewWithChildren, _RouteRecordBase } from 'vue-router'
import Layout from '@/layout/AppLayout.vue'
import { showProgressBar, closeProgressBar } from '@/components/progressBar'
import CssModule from '@/styles/config.module.scss'
import { useSystem } from '@/store/modules/system'
import { useUser } from '@/store/modules/user'
declare interface cRouteRecordSingleView extends RouteRecordSingleView {
  hidden?: boolean
}
declare interface cRouteRecordSingleViewWithChildren extends RouteRecordSingleViewWithChildren {
  hidden?: boolean
}
declare interface cRouteRecordMultipleViews extends RouteRecordMultipleViews {
  hidden?: boolean
}
declare interface cRouteRecordMultipleViewsWithChildren extends RouteRecordMultipleViewsWithChildren {
  hidden?: boolean
}
declare interface cRouteRecordRedirect extends RouteRecordRedirect {
  hidden?: boolean
}
declare type CustomRouteRecordRaw = cRouteRecordSingleView | cRouteRecordSingleViewWithChildren | cRouteRecordMultipleViews | cRouteRecordMultipleViewsWithChildren | cRouteRecordRedirect
export const routers: CustomRouteRecordRaw[] = [
  {
    path: '',
    redirect: '/home',
    hidden: true
  },
  {
    path: '/login',
    name: 'Login',
    component: async () => await import('@/views/login/index.vue'),
    hidden: true
  },
  {
    path: '',
    component: Layout,
    children: [
      {
        path: '/home',
        name: 'Home',
        component: async () => await import('@/views/home/index.vue'),
        meta: {
          title: '首页',
          icon: 'house'
        }
      }
    ]
  }
]
const router = createRouter({
  history: createWebHashHistory(),
  routes: routers
})
const whiteList = ['/login']
let isAddRouter: boolean = false
router.beforeEach(async (to, _from, next) => {
  showProgressBar({
    bgColor: CssModule.colorPrimary
  })
  const userStore = useUser()
  if (userStore.get.token !== undefined && userStore.get.token !== '' && userStore.get.token !== null) {
    if (to.path === '/login') {
      next('/home')
    }
    if (!isAddRouter) {
      isAddRouter = true
      const systemStore = useSystem()
      await systemStore.getMenuList()
      next({ path: to.path, query: to.query, replace: true })
    } else {
      next()
    }
    closeProgressBar()
  } else {
    if (whiteList.includes(to.path)) {
      next()
      closeProgressBar()
    } else {
      next('/login')
      closeProgressBar()
    }
  }
})
router.afterEach(() => {
  closeProgressBar()
})
export default router
